import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        resourceURL: wx.api.host + '/',
        search: '',
        list: [],
        tabs_active: 0,
        tab_column: {
            0: "全部",
            1: "待付款",
            2: "待发货",
            3: "待收货",
            4: "待评价",
            10: "售后",

        }, // tab选项卡标题
        status: {
            0: '全部',
            1: '待付款',
            2: '待发货',
            3: '待收货',
            4: '已完成',
            5: '已取消',
            6: '已退款',
            7: '申请退货',
            10: '退款中',
        }, // 订单状态
        // order_type: {
        //     1: '购买',
        //     2: '兑换'
        // }, //订单类型 1购买普通商品 2兑换商品
        page: 1,
        limit: 8,
        loading: false
    },

    // tab切换
    tabChange(even) {
        this.setData({
            tabs_active: even.detail.name,
            loading: false,
            page: 1,
            list: [],
        })
        // wx.setStorageSync('order', this.data.tabs_active.toString())
        this.getOrderList()
    },

    // 搜索
    onSearch(e) {
        this.setData({
            search: e.detail,
            loading: false,
            page: 1,
            list: [],
        })
        this.getOrderList()
    },
    // 查看详情
    detailed(e) {
        let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '../orderDetailed/index?id=' + id,
        })
    },
    // 联系客服
    remindDelivery(e) {
        let shop_id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '/pages/chat/index?shop_id' + shop_id,
        })
    },
    //复制
    copy(phone) {
        wx.setClipboardData({ //设置系统剪贴板的内容
            data: phone,
            success(res) {
                wx.getClipboardData({ // 获取系统剪贴板的内容
                    success(res) {
                        wx.showToast({
                            title: '复制成功',
                        })
                    }
                })
            }
        })
    },
    // 评价
    appraise(event) {
        let {
            detail_id,
            order_id
        } = event.target.dataset.id.children[0]

        // console.log(detail_id, order_id);
        wx.navigateTo({
            url: '/packageB/comments/oneComment/index?detail_id=' + detail_id + '&order_id=' + order_id
        })
    },
    // 撤回申请
    recall(e) {
        let id = e.currentTarget.dataset.id
        Dialog.confirm({
            title: '提示',
            message: '确认撤回申请吗？',
        }).then(() => {
            wx.http.post(wx.api.userafters, {
                order_id: id,
            }).then(res => {
                if (res.code == 1) {
                    Toast.success('已撤回申请')
                    setTimeout(() => {
                        this.setData({
                            page: 1,
                            list: []
                        })
                        this.getOrderList()
                    }, 1000);
                }
            })
        }).catch(() => {
            // on cancel
        });
    },
    //提醒发货
    remindOrder(e) {
        let id = e.currentTarget.dataset.id
        Dialog.confirm({
            title: '提示',
            message: '确认提醒发货吗？',
        }).then(() => {
            wx.http.post(wx.api.userremind, {
                order_id: id,
            }).then(res => {
                if (res.code == 1) {
                    setTimeout(() => {
                        this.setData({
                            page: 1,
                            list: []
                        })
                        this.getOrderList()
                    }, 1000);
                }
            })
        }).catch(() => {
            // on cancel
        });
    },
    // 取消订单
    cancelOrder(e) {
        let id = e.currentTarget.dataset.id
        Dialog.confirm({
            title: '提示',
            message: '确认取消订单吗？',
        }).then(() => {
            wx.http.post(wx.api.usercancel, {
                order_id: id,
            }).then(res => {
                if (res.code == 1) {
                    Toast.success('已取消订单')
                    setTimeout(() => {
                        this.setData({
                            page: 1,
                            list: []
                        })
                        this.getOrderList()
                    }, 1000);
                } 
            })
        }).catch(() => {
            // on cancel
        });
    },
    // 退款
    drawback(e) {
        // console.log(e.target.dataset.id);
        wx.navigateTo({
            url: '../AfterSales/index?order_id=' + e.target.dataset.id,
        })
    },
    // 查看物流
    logistics(e) {
        let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '../logistics/index?id=' + id,
        })
        // console.log(id);
    },
    // 删除订单
    delOrder(e) {
        let id = e.currentTarget.dataset.id
        Dialog.confirm({
            title: '提示',
            message: '确认删除订单吗？',
        }).then(() => {
            wx.http.post(wx.api.userwithdrawal, {
                a_s_id: id,
            }).then(res => {
                if (res.code == 1) {
                    Toast.success('已删除订单')
                    setTimeout(() => {
                        this.setData({
                            page: 1,
                            list: []
                        })
                        this.getOrderList()
                    }, 1000);
                }
            })
        }).catch(() => {
            // on cancel
        });
    },
    // 获取订单列表
    getOrderList() {
        Toast.loading({
            message: '加载中...',
            forbidClick: true,
            duration: 0,
        })
        // console.log(this.data.tabs_active);
        wx.http.get(wx.api.getorderlist, {
            order_type: 1,
            product_name: this.data.search, //搜索关键字
            status: this.data.tabs_active == 0 ? 0 : this.data.tabs_active, //订单状态 1未处理 2已处理 3...
            is_comment: this.data.tabs_active == 4 ? 2 : null, //订单是否已评价  1已经评价，2没有评价
            page: this.data.page, //页码
            limit: this.data.limit, //每页条数
        }).then(res => {
            // console.log(res);
            if (res.code == 1) {
                if (res.data.data.length > 0) {
                    this.setData({
                        list: [...this.data.list, ...res.data.data],
                        page: this.data.page + 1,
                        loading: true
                    })
                } else {
                    if (this.data.list.length > 0) {
                        Toast('没有更多了')
                    }
                }
                setTimeout(() => {
                    Toast.clear()
                }, 500);
            }
        })
    },

    // 确认收货
    confirmReceive(event) {
        // console.log(event);
        let id = event.currentTarget.dataset.id
        Dialog.confirm({
            title: '提示',
            message: '请问确认收到货了吗？',
        }).then(() => {
            wx.http.post(wx.api.usersure, {
                order_id: id,
            }).then(res => {
                if (res.code == 1) {
                    Toast.success('已确认收货')
                    setTimeout(() => {
                        this.setData({
                            page: 1,
                            list: []
                        })
                        this.getOrderList()
                    }, 1000);
                }
            })
        }).catch(() => {
            // on cancel
        });
    },

    // 订单详情 or 查看物流
    pageTo(event) {
        let id = event.currentTarget.dataset.id
        let url = event.currentTarget.dataset.url
        wx.navigateTo({
            url: `${url}?id=${id}`,
        })
    },
    // 支付
    payOrder(e) {
        console.log(e.currentTarget.dataset.id);
        let order_id = e.currentTarget.dataset.id
        wx.http.post(wx.api.tobepaid, {
            order_id: order_id,
            pay_end: 2
        }).then(res => {
            let {
                timeStamp,
                nonceStr,
                package: pa,
                signType,
                paySign
            } = res.data.data
            // console.log(res);
            wx.requestPayment({
                timeStamp,
                nonceStr,
                package: pa,
                signType,
                paySign,
                success:(res)=> {
                    wx.showToast({
                      title:'支付成功',
                      icon:'none'
                    })
                    this.setData({
                        list:[],
                        page:1
                    },this.getOrderList())
                },
                fail:(err)=> {
                    wx.showToast({
                        title:'支付失败',
                        icon:'none'
                    })
                    
                    // console.error(err);
                }
            })
        })
    },
    // 加入购物车
    Again(i) {
        let children = i.currentTarget.dataset.id.children
        // console.log(i);
        Promise.all(children.map(t => {
            return wx.http.post(wx.api.usereditcart, {
                quantity: t.quantity, //商品数量
                stock_id: t.p_s_id, //商品规格
                product_id: t.product_id //商品id
            })
        })).then(res => {
            // console.log(res);
            const cardid = res.map(t => t.data).join(',')
            // console.log(cardid);
            wx.navigateTo({
                url: '/pages/settlement/index?cart_ids=' + cardid,
            })
        }).catch(err => {
            // console.error(err);
            wx.showToast({
                title: '支付失败',
                icon: 'none'
            })
        })

    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // wx.setStorageSync('token', 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJvcGVuaWQiOiJvN0E5RXVCaUhDWXhsVG5md0syUWNGZnBubXFjIiwidGltZSI6MTY4MTI5MjI5NCwidXNlcl9pZCI6MzQzLCJuaWNrX25hbWUiOiJcdTU0MzRcdTZkYzdcdTk1MGIiLCJ0eXBlIjoib25saW5lIiwiZXhwIjoxNjg5OTMyMjk0fQ.Bye0JpYZ5AG2I7Kq5i4jb7lXptSDuN5yIm951dM7DKs')
        this.setData({
            tabs_active: options.status
        })

        this.getOrderList()

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        this.getOrderList()
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})